#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include <vector>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "Thread.hpp"

using task_t = std::function<void()>;

class MessageRoute
{
    bool IsExists(const InetAddr &addr)
    {
        for (auto a : _online_user_)
        {
            if (a == addr)
            {
                return true;
            }
        }
        return false;
    }
public:
    MessageRoute()
    {
    }

    void AddUser(InetAddr &user)
    {
        if (IsExists(user))
        {
            return;
        }
        _online_user_.push_back(user);
    }

    void DelUser(InetAddr &user)
    {
        for (auto item = _online_user_.begin(); item != _online_user_.end(); item++)
        {
            if (*item == user)
            {
                _online_user_.erase(item);
                return;
            }
        }
    }

    void RouteHelper(int sockfd, std::string message, InetAddr who)
    {
        for (auto u : _online_user_)
        {
            //不给发送的用户转发
            if(u.Port() == who.Port())
            continue;

            std::string send_message = "\n[" + who.Ip() + ":" + std::to_string(who.Port()) + "]# " + message + "\n";

            struct sockaddr_in clientaddr = u.Addr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
    }

    void Route(int sockfd, std::string message, InetAddr who)
    {
        AddUser(who);

        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }

        task_t t = std::bind(&MessageRoute::RouteHelper, this, sockfd, message, who);
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    }

    ~MessageRoute()
    {
    }

private:
    std::vector<InetAddr> _online_user_;
};